package cn.iocoder.yudao.module.reading.controller.app.community;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.*;

/**
 * 社区功能全局异常处理器
 *
 * @author 芋道源码
 */
@RestControllerAdvice("cn.iocoder.yudao.module.reading.controller.app.community")
@Slf4j
public class CommunityGlobalExceptionHandler {

    /**
     * 处理业务异常 ServiceException
     */
    @ExceptionHandler(ServiceException.class)
    public CommonResult<?> serviceExceptionHandler(ServiceException ex) {
        log.info("[serviceExceptionHandler][社区业务异常]", ex);
        return CommonResult.error(ex.getCode(), ex.getMessage());
    }

    /**
     * 处理参数校验异常 MethodArgumentNotValidException
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<?> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException ex) {
        log.warn("[methodArgumentNotValidExceptionHandler][参数校验异常]", ex);
        FieldError fieldError = ex.getBindingResult().getFieldError();
        assert fieldError != null;
        return CommonResult.error(BAD_REQUEST.getCode(), 
                String.format("请求参数不正确:%s", fieldError.getDefaultMessage()));
    }

    /**
     * 处理参数校验异常 BindException
     */
    @ExceptionHandler(BindException.class)
    public CommonResult<?> bindExceptionHandler(BindException ex) {
        log.warn("[bindExceptionHandler][参数绑定异常]", ex);
        FieldError fieldError = ex.getFieldError();
        assert fieldError != null;
        return CommonResult.error(BAD_REQUEST.getCode(), 
                String.format("请求参数不正确:%s", fieldError.getDefaultMessage()));
    }

    /**
     * 处理参数校验异常 ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public CommonResult<?> constraintViolationExceptionHandler(ConstraintViolationException ex) {
        log.warn("[constraintViolationExceptionHandler][参数约束异常]", ex);
        String message = ex.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(", "));
        return CommonResult.error(BAD_REQUEST.getCode(), 
                String.format("请求参数不正确:%s", message));
    }

    /**
     * 处理数据库唯一约束异常 DuplicateKeyException
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public CommonResult<?> duplicateKeyExceptionHandler(DuplicateKeyException ex) {
        log.warn("[duplicateKeyExceptionHandler][数据库唯一约束异常]", ex);
        
        String message = ex.getMessage();
        if (message != null) {
            if (message.contains("community_post_likes")) {
                return CommonResult.error(BAD_REQUEST.getCode(), "请勿重复点赞");
            } else if (message.contains("community_comment_likes")) {
                return CommonResult.error(BAD_REQUEST.getCode(), "请勿重复点赞评论");
            } else if (message.contains("community_work_collections")) {
                return CommonResult.error(BAD_REQUEST.getCode(), "请勿重复收藏");
            } else if (message.contains("community_reports")) {
                return CommonResult.error(BAD_REQUEST.getCode(), "请勿重复举报");
            }
        }
        
        return CommonResult.error(BAD_REQUEST.getCode(), "操作失败，请稍后重试");
    }

    /**
     * 处理文件上传大小超限异常 MaxUploadSizeExceededException
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public CommonResult<?> maxUploadSizeExceededExceptionHandler(MaxUploadSizeExceededException ex) {
        log.warn("[maxUploadSizeExceededExceptionHandler][文件上传大小超限]", ex);
        return CommonResult.error(BAD_REQUEST.getCode(), "上传文件大小超过限制");
    }

    /**
     * 处理系统异常
     */
    @ExceptionHandler(Exception.class)
    public CommonResult<?> defaultExceptionHandler(Exception ex) {
        log.error("[defaultExceptionHandler][社区功能系统异常]", ex);
        return CommonResult.error(INTERNAL_SERVER_ERROR.getCode(), "系统异常，请稍后重试");
    }

}
